#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:pengfeifu
@file: day_15_except.py 
@version:
@time: 2021/11/04 
@email:1324734112@qq.com
@desc：try___except
@function：常用函数
try 块允许您测试代码块以查找错误。
except 块允许您处理错误。
finally 块允许您执行代码，无论 try 和 except 块的结果如何。
raise 抛出异常
常见异常：
TypeError 类型异常
Exception 异常父类
NameError 变量异常，通常是未定义
"""
import json


def file_open():
    content = ""
    try:
        with open("../day_13_json/city.json", "rt", encoding="utf-8") as f:
            for line in f.readlines():
                content += line + "\n"
    except IOError:
        print("文件读取失败")
    finally:
        f.close()
    return content


def file_write(content):
    try:
        with open("A:\\city.json", "wb") as f:
            f.write(bytes(content, "utf-8"))
    except IOError:
        print("文件写入失败")
    finally:
        f.close()
    return None


def file_write_city():
    content = file_open()
    city_json = eval(content)
    city_map = {}
    for city in city_json["citys"]:
        city_key = city["id"]
        city_map[city_key] = city["value"]
    city_content = json.dumps(city_map, ensure_ascii=False, indent=4)
    file_write(city_content)


if __name__ == "__main__":
    file_write_city()
